package com.nuc.thread.reentrantlock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 诗酒趁年华
 * @version 1.0.0
 * @Description 条件变量
 * @createTime 2021年07月10日 16:14:00
 */
@Slf4j
public class Test4 {
    private static ReentrantLock room = new ReentrantLock();
    private static boolean hasCigarette = false;//是否有香烟
    private static boolean hasTakeOut = false;//是否有外卖
    private static Condition cigaretteCondition = room.newCondition();
    private static Condition takeOutCondition = room.newCondition();

    public static void main(String[] args) throws InterruptedException {
        new Thread(()->{
            room.lock();//获得锁
            try {
                log.debug("是否拿到香烟:{}",hasCigarette);
                while (!hasCigarette){
                    log.debug("没有香烟,不干活");
                    try {
                        cigaretteCondition.await();//进入香烟室等待
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("得到锁，开始干活");
            }finally {
                room.unlock();
            }
        },"t1").start();

        new Thread(()->{
            log.debug("是否拿到外卖:{}",hasTakeOut);
            room.lock();//获得锁
            try {
                while (!hasCigarette){
                    log.debug("没有外卖,不干活");
                    try {
                        takeOutCondition.await();//进入香烟室等待
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("得到锁，开始干活");
            }finally {
                room.unlock();
            }
        },"t2").start();

        Thread.sleep(1000);

        new Thread(()->{
            log.debug("开始送香烟");
            room.lock();
            try{
                hasCigarette = true;
                cigaretteCondition.signal();//唤醒在香烟室内的线程
            }finally {
                room.unlock();
            }
        },"送香烟").start();

        Thread.sleep(1000);
        new Thread(()->{
            log.debug("开始送外卖");
            room.lock();
            try{
                hasTakeOut = true;
                takeOutCondition.signal();//唤醒在香烟室内的线程
            }finally {
                room.unlock();
            }
        },"送外卖").start();
    }
}
